package com.sduept.nwld.dataserver.service.equipment.assessment.rest;

import com.sduept.bigdata.equipment.assessment.model.standarddict.HiddenDangerLevel;
import com.sduept.core.dao.SuperDAO;
import com.sduept.core.service.impl.StandardDictConfigurator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 问题设备统计分析
 * @author huangyu
 * @Date 2020年3月25日
 */
@RestController
@RequestMapping("/quesequipment")
public class QuestionEquipmentAnalysisService {
	
	@Autowired
	private SuperDAO dao;
	@Autowired
	private StandardDictConfigurator sdc;
	
	/**
	 * 获取指定年份范围内，全网的问题设备数量（按照风险等级进行统计）
	 * @param startYear
	 * @param endYear
	 * @return
	 */

	@GetMapping("getQuesEquipmentByYear/{startYear}/{endYear}")
	public List<QuesEquipmentDTO> getQuesEquipmentByYear(@PathVariable("startYear")String startYear,@PathVariable("endYear")String endYear) {
		if(StringUtils.isBlank(startYear) || StringUtils.isBlank(endYear)) {
			return new ArrayList<QuesEquipmentDTO>();
		}
		List<QuesEquipmentDTO> result = new ArrayList<QuesEquipmentDTO>();
		String t1 = startYear + "-01-01 00:00:00";
		String t2 = endYear + "-12-31 23:59:59";
		String sql = "SELECT FROM_UNIXTIME(et.updateTime/1000,'%Y') AS year, et.riskLevel, COUNT(*) AS count FROM  t_inspection_question_equipment et LEFT JOIN t_inspection_station st ON et.inspectionStationId=st.id WHERE et.updateTime>=UNIX_TIMESTAMP('"+t1+"')*100 AND et.updateTime<=UNIX_TIMESTAMP('"+t2+"')*1000 AND et.riskLevel IS NOT NULL GROUP BY year,et.riskLevel";
		List<?> lt = dao.nativeQuery(sql);
		List<QuesEquipmentDTO> qes = new ArrayList<QuesEquipmentDTO>();
		for (Object object : lt) {
			Object[] objs = (Object[])object;
			QuesEquipmentDTO qedto = new QuesEquipmentDTO();
			qedto.setGroupType(objs[0].toString());
			qedto.setRiskLevel(objs[1]!=null?objs[1].toString():null);
			qedto.setCount(objs[2].toString());
			qes.add(qedto);
		}
		// 补全数据，如缺失的年份、风险等级等
		result = complateDataByYear(Integer.parseInt(startYear), Integer.parseInt(endYear), qes);
		return result;
	}
	
	private List<QuesEquipmentDTO> complateDataByYear(int startYear,int endYear,List<QuesEquipmentDTO> list) {
		List<QuesEquipmentDTO> result = new ArrayList<QuesEquipmentDTO>();
		// 按年份进行统计，如果没有对应的风险等级数据，设置count=0
		List<HiddenDangerLevel> allLevels = dao.findAll(HiddenDangerLevel.class);
		Map<String, Map<String, List<QuesEquipmentDTO>>> map = list.stream().collect(Collectors.groupingBy(QuesEquipmentDTO::getGroupType,Collectors.groupingBy(QuesEquipmentDTO::getRiskLevel)));
		Map<String, List<QuesEquipmentDTO>> riskLevelMap = null;
		for (int year = startYear; year <= endYear; year++) {
			if(map.containsKey(year+"")) {
				// 为了使输出结果按照“一级、二级、三级、四级的顺序排序”
				riskLevelMap = map.get(year+"");
				for (HiddenDangerLevel hiddenDangerLevel : allLevels) {
					if(!riskLevelMap.containsKey(hiddenDangerLevel.getName())) {
						QuesEquipmentDTO qedto = new QuesEquipmentDTO();
						qedto.setGroupType(year+"");
						qedto.setRiskLevel(hiddenDangerLevel.getName());
						qedto.setCount("0");
						result.add(qedto);
					} else {
						result.addAll(riskLevelMap.get(hiddenDangerLevel.getName()));
					}
				}
			} else {
				// 没有当年的数据，补0
				for (HiddenDangerLevel hiddenDangerLevel : allLevels) {
					QuesEquipmentDTO qedto = new QuesEquipmentDTO();
					qedto.setGroupType(year+"");
					qedto.setRiskLevel(hiddenDangerLevel.getName());
					qedto.setCount("0");
					result.add(qedto);
				}
			}
		}
		return result;
	}
	
	/**
	 * 获取指定年份的不同分子公司的问题设备数量统计
	 * @param year
	 * @return
	 */

	@GetMapping("getQuesEquipmentGroupByComp/{year}")

	public List<QuesEquipmentDTO> getQuesEquipmentGroupByComp(@PathVariable("year")String year) {
		if(StringUtils.isBlank(year)) {
			return new ArrayList<QuesEquipmentDTO>();
		}
		List<QuesEquipmentDTO> result = new ArrayList<QuesEquipmentDTO>();
		String t1 = year + "-01-01 00:00:00";
		String t2 = year + "-12-31 23:59:59";
		String sql = "SELECT st.acceptScope, et.riskLevel, COUNT(*) AS count FROM t_inspection_question_equipment et LEFT JOIN t_inspection_station st ON et.inspectionStationId=st.id WHERE et.updateTime>=UNIX_TIMESTAMP('"+t1+"')*100 AND et.updateTime<=UNIX_TIMESTAMP('"+t2+"')*1000 AND et.riskLevel IS NOT NULL AND st.acceptScope IS NOT NULL GROUP BY st.acceptScope,et.riskLevel";
		List<?> lt = dao.nativeQuery(sql);
		List<QuesEquipmentDTO> qes = new ArrayList<QuesEquipmentDTO>();
		for (Object object : lt) {
			Object[] objs = (Object[])object;
			QuesEquipmentDTO qedto = new QuesEquipmentDTO();
			qedto.setGroupType(objs[0]!=null?objs[0].toString():null);
			qedto.setRiskLevel(objs[1]!=null?objs[1].toString():null);
			qedto.setCount(objs[2].toString());
			qes.add(qedto);
		}
		// 补全数据，如缺失的年份、风险等级等
		result = complateDataByAcceptUnit(qes);
		return result;
	}
	
	/**
	 * 获取指定年份、指定分子公司下的各个供电局的问题设备数量统计
	 * @param year
	 * @return
	 */

	@GetMapping("getQuesEquipmentCountByUnit/{year}/{acceptScope}")
	public List<QuesEquipmentDTO> getQuesEquipmentCountByUnit(@PathVariable("year")String year,@PathVariable("acceptScope")String acceptScope) {
		if(StringUtils.isBlank(year)) {
			return new ArrayList<QuesEquipmentDTO>();
		}
		List<QuesEquipmentDTO> result = new ArrayList<QuesEquipmentDTO>();
		String t1 = year + "-01-01 00:00:00";
		String t2 = year + "-12-31 23:59:59";
		String sql = "SELECT st.acceptUnit, et.riskLevel, COUNT(*) AS count FROM t_inspection_question_equipment et LEFT JOIN t_inspection_station st ON et.inspectionStationId=st.id WHERE st.acceptScope='"+acceptScope+"' AND et.updateTime>=UNIX_TIMESTAMP('"+t1+"')*100 AND et.updateTime<=UNIX_TIMESTAMP('"+t2+"')*1000 AND et.riskLevel IS NOT NULL AND st.acceptScope IS NOT NULL GROUP BY st.acceptUnit,et.riskLevel";
		List<?> lt = dao.nativeQuery(sql);
		List<QuesEquipmentDTO> qes = new ArrayList<QuesEquipmentDTO>();
		for (Object object : lt) {
			Object[] objs = (Object[])object;
			QuesEquipmentDTO qedto = new QuesEquipmentDTO();
			qedto.setGroupType(objs[0]!=null?objs[0].toString():null);
			qedto.setRiskLevel(objs[1]!=null?objs[1].toString():null);
			qedto.setCount(objs[2].toString());
			qes.add(qedto);
		}
		// 补全数据
		result = complateDataByAcceptUnit(qes);
		return result;
	}
	
	private List<QuesEquipmentDTO> complateDataByAcceptUnit(List<QuesEquipmentDTO> list) {
		List<QuesEquipmentDTO> result = new ArrayList<QuesEquipmentDTO>();
		List<HiddenDangerLevel> allLevels = dao.findAll(HiddenDangerLevel.class);
		Map<String, Map<String, List<QuesEquipmentDTO>>> map = list.stream().collect(Collectors.groupingBy(QuesEquipmentDTO::getGroupType,Collectors.groupingBy(QuesEquipmentDTO::getRiskLevel)));
		Map<String, List<QuesEquipmentDTO>> riskLevelMap = null;
		for (String acceptUnit : map.keySet()) {
			// 为了使输出结果按照“一级、二级、三级、四级、建议级”的顺序排序
			riskLevelMap = map.get(acceptUnit);
			for (HiddenDangerLevel hiddenDangerLevel : allLevels) {
				if(!riskLevelMap.containsKey(hiddenDangerLevel.getName())) {
					QuesEquipmentDTO qedto = new QuesEquipmentDTO();
					qedto.setGroupType(acceptUnit);
					qedto.setRiskLevel(hiddenDangerLevel.getName());
					qedto.setCount("0");
					result.add(qedto);
				} else {
					result.addAll(riskLevelMap.get(hiddenDangerLevel.getName()));
				}
			}
		}
		return result;
	}
	
	class QuesEquipmentDTO {
		/**
		 * 统计标准，年/分子公司/供电局
		 */
		private String groupType;
		/**
		 * 问题设备数量
		 */
		private String count;
		
		/**
		 * 风险等级
		 */
		private String riskLevel;

		public String getCount() {
			return count;
		}

		public String getRiskLevel() {
			return riskLevel;
		}

		public void setCount(String count) {
			this.count = count;
		}

		public void setRiskLevel(String riskLevel) {
			this.riskLevel = riskLevel;
		}

		public String getGroupType() {
			return groupType;
		}

		public void setGroupType(String groupType) {
			this.groupType = groupType;
		}

	}
	
}
